/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.funda.xmppserver.handlers;

import com.funda.xmppserver.ComponentParser;
import com.funda.xmppserver.XMPPInfo;
import com.funda.xmppserver.writer.XMPPPacketWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 *
 * @author kurinchi
 */
public class StreamHandler implements ComponentParser {

    XMPPPacketWriter packetwriter;
    Boolean valid = false;
    Map<Object, Object> attribs = new HashMap<Object, Object>();
    ArrayList<Object> ns = new ArrayList<Object>();

    public StreamHandler(XMPPPacketWriter packetwriter) {
        this.packetwriter = packetwriter;

        attribs.put("to", XMPPInfo.getHOST());
        attribs.put("version", "1.0");
        attribs.put("lang", "en");

        ns.add("jabber:client");
        ns.add("http://etherx.jabber.org/streams");
    }

    public void parseElement(XMLStreamReader xmlReader) throws XMLStreamException {
        System.out.println("Stream!!");

        if (xmlReader.getPrefix().equalsIgnoreCase("stream")) {
            valid = true;
        }

        //checks all attributes
        for (int i = 0; i < xmlReader.getAttributeCount(); i++) {
            //System.out.println(xmlReader.getAttributeLocalName(i) + " -> " + xmlReader.getAttributeValue(i));
            String attribname = xmlReader.getAttributeLocalName(i);
            String attribval = xmlReader.getAttributeValue(i);
            if (!(attribs.containsKey(attribname) && (attribval.equalsIgnoreCase(attribs.get(attribname).toString())))) {
                valid = false;
            }

        }

        //checks namespace
        for (int i = 0; i < xmlReader.getNamespaceCount(); i++) {
            //System.out.println(xmlReader.getNamespaceURI(i));
            String nsname = xmlReader.getNamespaceURI(i);
            if (!ns.contains(nsname)) {
                valid = false;
            }
        }
        System.out.println("Stream Result : " + valid);
        if (valid) {
            packetwriter.sendStreamResponse();
        }
    }
}
